package com.fulei.logic;

import android.annotation.SuppressLint;
import com.bjfl.saleManager.util.HexByteDumper;
import com.bjfl.saleManager.util.LogUtil;
import com.dwin.navy.serialportapi.SerailPortOpt;

@SuppressLint({"SdCardPath"})
public class CodeReader
{
  private static SerailPortOpt serialPort = null;
  public static String comNo = "";
  public static String baudRate = "";
  public static byte controlPanelInfo;
  
  public static boolean OpenPort()
  {
    try
    {
      serialPort = new SerailPortOpt();
      
      serialPort.mDevNum = Integer.parseInt(comNo);
      serialPort.mSpeed = Integer.parseInt(baudRate);
      serialPort.mDataBits = 8;
      serialPort.mStopBits = 1;
      serialPort.mParity = 110;
      if (serialPort.mFd == null)
      {
        serialPort.openDev(serialPort.mDevNum);
        serialPort.setSpeed(serialPort.mFd, serialPort.mSpeed);
        serialPort.setParity(serialPort.mFd, serialPort.mDataBits, serialPort.mStopBits, serialPort.mParity);
      }
    }
    catch (Exception ex)
    {
      LogUtil.writeExceptionLog(ex.getMessage());
    }
    return true;
  }
  
  public static void closeSerialPort()
  {
    try
    {
      if (serialPort.mFd != null) {
        serialPort.closeDev(serialPort.mFd);
      }
      serialPort.mFd = null;
      serialPort = null;
    }
    catch (Exception ex)
    {
      LogUtil.writeExceptionLog(ex.getMessage());
    }
  }
  
  public static String codeRead()
  {
    String return_data = "";
    try
    {
      if (serialPort == null) {
        OpenPort();
      }
      if (serialPort.mFd == null)
      {
        serialPort.openDev(serialPort.mDevNum);
        serialPort.setSpeed(serialPort.mFd, serialPort.mSpeed);
        serialPort.setParity(serialPort.mFd, serialPort.mDataBits, serialPort.mStopBits, serialPort.mParity);
      }
      byte[] ReadData = new byte[512];
      int ReadDataLength = serialPort.readBytes(ReadData, 100, 30);
      if (ReadDataLength < 1) {
        return null;
      }
      LogUtil.writeCodeLog(
        "CodeRead:" + LogUtil.bytesToHexString(ReadData, ReadDataLength));
      if (ReadDataLength > 10)
      {
        byte[] buffer = new byte[ReadDataLength];
        serialPort.getInputStream().read(buffer);
        System.arraycopy(ReadData, 0, buffer, 0, ReadDataLength);
        String code = getStringFromData(buffer, 0, buffer.length);
        if ((buffer[(buffer.length - 1)] == 13) && (buffer[(buffer.length - 2)] == 10)) {
          return_data = code;
        }
      }
    }
    catch (Exception ex)
    {
      LogUtil.writeCoinAcceptorInfo("扫码指令异常:" + ex.getMessage());
      return_data = null;
    }
    return return_data;
  }
  
  public static String getStringFromData(byte[] data, int start, int len)
  {
    byte[] bts = new byte[len];
    System.arraycopy(data, start, bts, 0, len);
    return HexByteDumper.toStringHex(HexByteDumper.getHexDump(bts));
  }
}
